package com.example.cloudmusic.home.repository

import com.example.cloudmusic.home.model.*
import com.example.cm_network.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import android.util.Log
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 网络数据源策略实现
 * 从网络API获取数据
 */
class NetworkDataSourceStrategy(private val apiService: ApiService) : DataSourceStrategy {

    private val TAG = "NetworkDataSource"

    /**
     * 错误处理的辅助方法
     */
    private fun logError(method: String, e: Exception) {
        Log.e(TAG, "$method 失败: ${e.javaClass.simpleName} - ${e.message}", e)
        when (e) {
            is UnknownHostException -> Log.e(TAG, "无法连接到服务器，请检查服务器是否启动", e)
            is SocketTimeoutException -> Log.e(TAG, "请求超时，服务器响应时间过长", e)
            is ConnectException -> Log.e(TAG, "连接服务器失败，服务器可能已关闭", e)
            else -> Log.e(TAG, "未知错误: ${e.message}", e)
        }
    }

    /**
     * 获取轮播图数据
     */
    override suspend fun getBanners(): Result<List<Banner>> = withContext(Dispatchers.IO) {
        try {
            val response = apiService.getBanners()
            if (response.code == 200) {
                val banners = response.banners.map { bannerData ->
                    Banner(
                        id = bannerData.targetId,
                        imageUrl = bannerData.imageUrl
                    )
                }
                Result.success(banners)
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取轮播图", e)
            Result.failure(e)
        }
    }
    
    /**
     * 获取推荐歌单
     */
    override suspend fun getRecommendedPlaylists(): Result<List<Playlist>> = withContext(Dispatchers.IO) {
        try {
            // 从首页推荐API获取数据
            val response = apiService.getHomeRecommend()
            if (response.code == 200) {
                // 查找歌单数据块
                val blocks = response.data.blocks
                Log.d(TAG, "获取到blocks: ${blocks.size}个, blockCodes: ${blocks.map { it.blockCode }}")
                
                // 服务器返回的blockCode是"PLAYLIST_RCMD"而不是"HOMEPAGE_BLOCK_PLAYLIST_RCMD"
                val playlistBlocks = blocks.find { it.blockCode == "PLAYLIST_RCMD" }
                if (playlistBlocks != null) {
                    Log.d(TAG, "找到推荐歌单块: ${playlistBlocks.title}, 包含${playlistBlocks.items.size}个歌单")
                    
                    // 转换为Playlist模型
                    val playlists = playlistBlocks.items.mapNotNull { item ->
                        try {
                            // 将item强制转换为Map<String, Any>
                            @Suppress("UNCHECKED_CAST")
                            val itemMap = item as? Map<String, Any>
                            if (itemMap != null) {
                                val id = itemMap["id"]?.toString() ?: ""
                                val name = itemMap["name"]?.toString() ?: ""
                                val coverImgUrl = itemMap["coverImgUrl"]?.toString() ?: ""
                                val description = itemMap["description"]?.toString() ?: ""
                                val playCount = (itemMap["playCount"] as? Number)?.toLong() ?: 0L
                                
                                Playlist(
                                    id = id,
                                    title = name,
                                    artist = "",  // 创建者信息可能没有
                                    imageUrl = coverImgUrl,
                                    playCount = playCount,
                                    description = description,
                                    musics = emptyList()  // 暂不获取详细歌曲数据
                                )
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "解析歌单数据失败", e)
                            null
                        }
                    }
                    Log.d(TAG, "成功解析${playlists.size}个歌单")
                    Result.success(playlists)
                } else {
                    Log.e(TAG, "找不到推荐歌单数据块")
                    Result.failure(Exception("找不到推荐歌单数据"))
                }
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取推荐歌单", e)
            Result.failure(e)
        }
    }
    
    /**
     * 获取热门艺人
     */
    override suspend fun getHotArtists(): Result<List<Artist>> = withContext(Dispatchers.IO) {
        try {
            // 从首页推荐API获取数据
            val response = apiService.getHomeRecommend()
            if (response.code == 200) {
                // 查找艺人数据块
                val artistBlocks = response.data.blocks.find { it.blockCode == "ARTIST_RCMD" }
                if (artistBlocks != null) {
                    Log.d(TAG, "找到推荐艺人块: ${artistBlocks.title}, 包含${artistBlocks.items.size}个艺人")
                    
                    // 转换为Artist模型
                    val artists = artistBlocks.items.mapNotNull { item ->
                        try {
                            // 将item强制转换为Map<String, Any>
                            @Suppress("UNCHECKED_CAST")
                            val itemMap = item as? Map<String, Any>
                            if (itemMap != null) {
                                val id = itemMap["id"]?.toString() ?: ""
                                val name = itemMap["name"]?.toString() ?: ""
                                val picUrl = itemMap["picUrl"]?.toString() ?: ""
                                
                                Artist(
                                    id = id,
                                    name = name,
                                    imageUrl = picUrl,
                                    followers = 0L,  // API没有返回粉丝数
                                    musics = emptyList()  // 暂不获取详细歌曲数据
                                )
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "解析艺人数据失败", e)
                            null
                        }
                    }
                    Log.d(TAG, "成功解析${artists.size}个艺人")
                    Result.success(artists)
                } else {
                    Log.e(TAG, "找不到推荐艺人数据块")
                    // 尝试使用单独的艺人API
                    try {
                        val artistResponse = apiService.getRecommendArtists()
                        if (artistResponse.code == 200) {
                            val artists = artistResponse.artists.map { artistData ->
                                Artist(
                                    id = artistData.id,
                                    name = artistData.name,
                                    imageUrl = artistData.picUrl,
                                    followers = 0L,
                                    musics = emptyList()
                                )
                            }
                            Result.success(artists)
                        } else {
                            Result.failure(Exception("API请求失败，错误码：${artistResponse.code}"))
                        }
                    } catch (e: Exception) {
                        logError("获取推荐艺人备选方案", e)
                        Result.failure(e)
                    }
                }
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取推荐艺人", e)
            Result.failure(e)
        }
    }
    
    /**
     * 获取个人歌单
     */
    override suspend fun getPersonalPlaylists(): Result<List<Playlist>> = withContext(Dispatchers.IO) {
        try {
            // 从首页推荐API获取数据
            val response = apiService.getHomeRecommend()
            if (response.code == 200) {
                // 查找个人歌单数据块
                val personalPlaylistBlocks = response.data.blocks.find { it.blockCode == "PERSONAL_PLAYLIST" }
                if (personalPlaylistBlocks != null) {
                    Log.d(TAG, "找到个人歌单块: ${personalPlaylistBlocks.title}, 包含${personalPlaylistBlocks.items.size}个歌单")
                    
                    // 转换为Playlist模型
                    val playlists = personalPlaylistBlocks.items.mapNotNull { item ->
                        try {
                            // 将item强制转换为Map<String, Any>
                            @Suppress("UNCHECKED_CAST")
                            val itemMap = item as? Map<String, Any>
                            if (itemMap != null) {
                                val id = itemMap["id"]?.toString() ?: ""
                                val name = itemMap["name"]?.toString() ?: ""
                                val coverImgUrl = itemMap["coverImgUrl"]?.toString() ?: ""
                                val description = itemMap["description"]?.toString() ?: ""
                                val playCount = (itemMap["playCount"] as? Number)?.toLong() ?: 0L
                                
                                Playlist(
                                    id = id,
                                    title = name,
                                    artist = "",  // 创建者信息可能没有
                                    imageUrl = coverImgUrl,
                                    playCount = playCount,
                                    description = description,
                                    musics = emptyList()  // 暂不获取详细歌曲数据
                                )
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "解析个人歌单数据失败", e)
                            null
                        }
                    }
                    Log.d(TAG, "成功解析${playlists.size}个个人歌单")
                    Result.success(playlists)
                } else {
                    Log.e(TAG, "找不到个人歌单数据块")
                    // 备用方案：返回部分推荐歌单
                    val recommendResult = getRecommendedPlaylists()
                    if (recommendResult.isSuccess) {
                        val playlists = recommendResult.getOrNull()?.take(5) ?: emptyList()
                        Result.success(playlists)
                    } else {
                        Result.failure(recommendResult.exceptionOrNull() ?: Exception("获取个人歌单失败"))
                    }
                }
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取个人歌单", e)
            Result.failure(e)
        }
    }
    
    /**
     * 获取音乐风格
     */
    override suspend fun getMusicStyles(): Result<List<MusicStyle>> = withContext(Dispatchers.IO) {
        try {
            // 从首页推荐API获取数据
            val response = apiService.getHomeRecommend()
            if (response.code == 200) {
                // 查找音乐风格数据块
                val musicStyleBlocks = response.data.blocks.find { it.blockCode == "MUSIC_STYLE" }
                if (musicStyleBlocks != null) {
                    Log.d(TAG, "找到音乐风格块: ${musicStyleBlocks.title}, 包含${musicStyleBlocks.items.size}个风格")
                    
                    // 转换为MusicStyle模型
                    val musicStyles = musicStyleBlocks.items.mapNotNull { item ->
                        try {
                            // 将item强制转换为Map<String, Any>
                            @Suppress("UNCHECKED_CAST")
                            val itemMap = item as? Map<String, Any>
                            if (itemMap != null) {
                                val style = itemMap["style"]?.toString() ?: ""
                                val imageUrl = itemMap["imageUrl"]?.toString() ?: ""
                                
                                // 风格关联的歌单
                                val playlists = (itemMap["playlists"] as? List<*>)?.mapNotNull { playlistItem ->
                                    @Suppress("UNCHECKED_CAST")
                                    val playlistMap = playlistItem as? Map<String, Any>
                                    if (playlistMap != null) {
                                        val id = playlistMap["id"]?.toString() ?: ""
                                        val name = playlistMap["name"]?.toString() ?: ""
                                        val coverImgUrl = playlistMap["coverImgUrl"]?.toString() ?: ""
                                        val desc = playlistMap["description"]?.toString() ?: ""
                                        val count = (playlistMap["playCount"] as? Number)?.toLong() ?: 0L
                                        
                                        Playlist(
                                            id = id,
                                            title = name,
                                            artist = "",
                                            imageUrl = coverImgUrl,
                                            playCount = count,
                                            description = desc,
                                            musics = emptyList()
                                        )
                                    } else {
                                        null
                                    }
                                } ?: emptyList()
                                
                                MusicStyle(
                                    style = style,
                                    imageUrl = imageUrl,
                                    musics = playlists
                                )
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "解析音乐风格数据失败", e)
                            null
                        }
                    }
                    Log.d(TAG, "成功解析${musicStyles.size}个音乐风格")
                    Result.success(musicStyles)
                } else {
                    Log.e(TAG, "找不到音乐风格数据块，尝试替代方案")
                    // API没有直接提供音乐风格数据，可以通过搜索不同风格的歌曲来组合
                    val styles = listOf("摇滚", "流行", "民谣", "电子", "嘻哈")
                    val musicStyles = styles.map { style ->
                        // 搜索该风格的歌曲/歌单
                        val searchResponse = apiService.search(style, 1000, 3)
                        val playlists = if (searchResponse.code == 200 && searchResponse.result.playlists != null) {
                            searchResponse.result.playlists!!.map { playlistData ->
                                Playlist(
                                    id = playlistData.id,
                                    title = playlistData.name,
                                    artist = "", // 可能需要从playlist中获取创建者信息
                                    imageUrl = playlistData.coverImgUrl,
                                    playCount = playlistData.playCount,
                                    description = playlistData.description,
                                    musics = emptyList() // 暂不加载歌曲列表
                                )
                            }
                        } else {
                            emptyList()
                        }
                        
                        MusicStyle(
                            style = style,
                            imageUrl = playlists.firstOrNull()?.imageUrl ?: "",
                            musics = playlists
                        )
                    }
                    Result.success(musicStyles)
                }
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取音乐风格", e)
            Result.failure(e)
        }
    }
    
    /**
     * 获取推荐歌曲
     */
    override suspend fun getRecommendedMusics(): Result<List<Music>> = withContext(Dispatchers.IO) {
        try {
            // 从首页推荐API获取数据
            val response = apiService.getHomeRecommend()
            if (response.code == 200) {
                // 查找推荐歌曲数据块
                val songBlocks = response.data.blocks.find { it.blockCode == "RECOMMENDED_MUSICS" }
                if (songBlocks != null) {
                    Log.d(TAG, "找到推荐歌曲块: ${songBlocks.title}, 包含${songBlocks.items.size}首歌曲")
                    
                    // 转换为Music模型
                    val songs = songBlocks.items.mapNotNull { item ->
                        try {
                            // 将item强制转换为SongData或Map
                            if (item is com.example.cm_network.SongData) {
                                convertSong(item)
                            } else {
                                // 作为Map处理
                                @Suppress("UNCHECKED_CAST")
                                val itemMap = item as? Map<String, Any>
                                if (itemMap != null) {
                                    val id = itemMap["id"]?.toString() ?: ""
                                    val name = itemMap["name"]?.toString() ?: ""
                                    
                                    // 提取艺术家信息
                                    val artistName = if (itemMap.containsKey("artists")) {
                                        @Suppress("UNCHECKED_CAST")
                                        val artists = itemMap["artists"] as? List<Map<String, Any>>
                                        artists?.firstOrNull()?.get("name")?.toString() ?: ""
                                    } else {
                                        ""
                                    }
                                    
                                    // 提取专辑信息
                                    val album = if (itemMap.containsKey("album")) {
                                        @Suppress("UNCHECKED_CAST")
                                        val albumMap = itemMap["album"] as? Map<String, Any>
                                        albumMap?.get("name")?.toString() ?: ""
                                    } else {
                                        ""
                                    }
                                    
                                    // 提取图片URL
                                    val imageUrl = if (itemMap.containsKey("album")) {
                                        @Suppress("UNCHECKED_CAST")
                                        val albumMap = itemMap["album"] as? Map<String, Any>
                                        albumMap?.get("picUrl")?.toString() ?: ""
                                    } else {
                                        ""
                                    }
                                    
                                    val duration = (itemMap["duration"] as? Number)?.toLong() ?: 0L
                                    val isVip = (itemMap["isVip"] as? Boolean) ?: false
                                    val isFavorite = (itemMap["isFavorite"] as? Boolean) ?: false
                                    val type = itemMap["type"]?.toString() ?: "未知"
                                    
                                    Music(
                                        id = id,
                                        title = name,
                                        artist = artistName,
                                        album = album,
                                        imageUrl = imageUrl,
                                        duration = duration,
                                        playUrl = itemMap["playUrl"]?.toString() ?: "",
                                        isVip = isVip,
                                        isFavorite = isFavorite,
                                        type = type
                                    )
                                } else {
                                    null
                                }
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "解析推荐歌曲数据失败", e)
                            null
                        }
                    }
                    Log.d(TAG, "成功解析${songs.size}首推荐歌曲")
                    Result.success(songs)
                } else {
                    Log.e(TAG, "找不到推荐歌曲数据块")
                    Result.failure(Exception("找不到推荐歌曲数据"))
                }
            } else {
                Log.e(TAG, "API请求失败，错误码：${response.code}")
                Result.failure(Exception("API请求失败，错误码：${response.code}"))
            }
        } catch (e: Exception) {
            logError("获取推荐歌曲", e)
            Result.failure(e)
        }
    }
    
    /**
     * 转换API返回的歌曲数据为应用模型
     */
    private fun convertSong(songData: com.example.cm_network.SongData): Music {
        return Music(
            id = songData.id,
            title = songData.name,
            artist = songData.artists.firstOrNull()?.name ?: "",
            album = songData.album.name,
            imageUrl = songData.album.picUrl,
            duration = songData.duration,
            playUrl = "", // 需要通过单独的API获取播放链接
            isVip = false, // 需要根据API返回的信息判断
            isFavorite = false,
            type = "未知" // 可能需要额外的API或从分类信息中推断
        )
    }
    
    /**
     * 转换API返回的歌曲数据列表为应用模型
     */
    private fun convertSongs(songs: List<com.example.cm_network.SongData>): List<Music> {
        return songs.map { convertSong(it) }
    }
} 